//
//  HMEmoticonKeyBoardView.swift
//  Black22
//
//  Created by Apple on 16/11/26.
//  Copyright © 2016年 KY. All rights reserved.
//

import UIKit
/*
    1. 表情视图-> UICollectionView
    2. 页数指示器-> UIPageControl
    3. toolbar -> UIStackView
 */
//  重用标记
private let HMEmotionCollectionViewCellIdentifier = "HMEmotionCollectionViewCellIdentifier"
//  表情键盘视图
class HMEmoticonKeyBoardView: UIView {
    
    // MARK:    --懒加载
    fileprivate lazy var emoticonCollectionView: UICollectionView = {
        let flowLayout = UICollectionViewFlowLayout()
        //  设置水平滚动
        flowLayout.scrollDirection = .horizontal
        
        let collectionView = UICollectionView(frame: CGRect.zero, collectionViewLayout: flowLayout)
        //  注册cell
        collectionView.register(HMEmoticonCollectionViewCell.self, forCellWithReuseIdentifier: HMEmotionCollectionViewCellIdentifier)
        //  设置数据源代理
        collectionView.dataSource = self
        //  设置代理
        collectionView.delegate = self
        //  去掉滚动条
        collectionView.showsVerticalScrollIndicator = false

        collectionView.showsHorizontalScrollIndicator = false
        //  开启分页
        collectionView.isPagingEnabled = true
        //  弹簧效果去掉
        collectionView.bounces = false
    
        
        //  设置表情视图的颜色等于当前表情键盘的颜色
        collectionView.backgroundColor = self.backgroundColor
        return collectionView
    }()
    
    //  页数指示器
    fileprivate lazy var pageControl: UIPageControl = {
        let ctr = UIPageControl()
        //  隐藏单页
        ctr.hidesForSinglePage = true
        ctr.currentPageIndicatorTintColor = UIColor(patternImage: UIImage(named:"compose_keyboard_dot_selected")!)
        ctr.pageIndicatorTintColor = UIColor(patternImage: UIImage(named: "compose_keyboard_dot_normal")!)
        return ctr
    }()
    fileprivate lazy var toolBar: HMEmoticonToolBar = HMEmoticonToolBar()
    
    override init(frame: CGRect) {
        super.init(frame: frame)
        setupUI()
    }
    
    required init?(coder aDecoder: NSCoder) {
        fatalError("init(coder:) has not been implemented")
    }
    
    private func setupUI() {
        
        //  默认这组数据选中
        let currentIndexPath = IndexPath(item: 0, section: 1)
        
        //  主线程异步，等到其它视图创建完成和数据绑定完成，滚动到指定位置
        DispatchQueue.main.async {
            self.emoticonCollectionView.scrollToItem(at: currentIndexPath, at: .left, animated: false)
            //  设置页数指示器数据
            self.setPageControlData(indexPath: currentIndexPath)
        }
        
        
        
        backgroundColor = UIColor(patternImage: UIImage(named: "emoticon_keyboard_background")!)
        
        addSubview(emoticonCollectionView)
        addSubview(pageControl)
        addSubview(toolBar)
        emoticonCollectionView.snp_makeConstraints { (make) in
            make.leading.equalTo(self)
            make.top.equalTo(self)
            make.trailing.equalTo(self)
            make.bottom.equalTo(toolBar.snp_top)
        }
        pageControl.snp_makeConstraints { (make) in
            make.bottom.equalTo(emoticonCollectionView)
            make.centerX.equalTo(emoticonCollectionView)
            make.height.equalTo(10)
        }
        toolBar.snp_makeConstraints { (make) in
            make.bottom.equalTo(self)
            make.leading.equalTo(self)
            make.trailing.equalTo(self)
            make.height.equalTo(35)
        }
        
        
        toolBar.callBack = { [weak self] (type: HMEmoticonToolBarType) -> Void in
            let indexPath: IndexPath
            switch type {
            case .recent:
                print("最近")
                indexPath = IndexPath(item: 0, section: 0)
            case .normal:
                print("默认")
                indexPath = IndexPath(item: 0, section: 1)
            
            case .emoji:
                print("emoji")
                indexPath = IndexPath(item: 0, section: 2)
            case .lxh:
                print("浪小花")
                indexPath = IndexPath(item: 0, section: 3)
            }
            //  滚动到指定的indexpath
            self?.emoticonCollectionView.scrollToItem(at: indexPath, at: .left, animated: false)
            self?.setPageControlData(indexPath: indexPath)
        }
        
        
        
        
    }
    
    //  表情视图确定大小，设置每项条目的大小
    override func layoutSubviews() {
        super.layoutSubviews()
        
        
        let flowLayout = self.emoticonCollectionView.collectionViewLayout as! UICollectionViewFlowLayout
        //  每页大小等于表情视图的大小
        flowLayout.itemSize = self.emoticonCollectionView.size
        flowLayout.minimumLineSpacing = 0
        flowLayout.minimumInteritemSpacing = 0
        
        
    }
    
    
    
    //  根据indexPath绑定数据
    fileprivate func setPageControlData(indexPath: IndexPath) {
        pageControl.numberOfPages = HMEmoticonTools.sharedTools.allEmoticonArray[indexPath.section].count
        pageControl.currentPage = indexPath.item
        
    }

    //  刷新最近表情这组数据
    func reloadRecentData() {
        let indexPath = IndexPath(item: 0, section: 0)
        //  重新加载最近表情这组数据
        self.emoticonCollectionView.reloadItems(at: [indexPath])
    }
    
}


extension HMEmoticonKeyBoardView: UICollectionViewDataSource, UICollectionViewDelegate {
    
    func numberOfSections(in collectionView: UICollectionView) -> Int {
        return HMEmoticonTools.sharedTools.allEmoticonArray.count
    }
    
    func collectionView(_ collectionView: UICollectionView, numberOfItemsInSection section: Int) -> Int {
        return HMEmoticonTools.sharedTools.allEmoticonArray[section].count
    }
    
    func collectionView(_ collectionView: UICollectionView, cellForItemAt indexPath: IndexPath) -> UICollectionViewCell {
        let cell = collectionView.dequeueReusableCell(withReuseIdentifier: HMEmotionCollectionViewCellIdentifier, for: indexPath) as! HMEmoticonCollectionViewCell
        
        cell.emoticonArray = HMEmoticonTools.sharedTools.allEmoticonArray[indexPath.section][indexPath.item]
        cell.indexPath = indexPath
        return cell
    }
    
    func scrollViewDidScroll(_ scrollView: UIScrollView) {
        //  计算collectionview内容的中心点
        let currentCenterX = scrollView.contentOffset.x + scrollView.width / 2
        let currentCenterY = scrollView.contentOffset.y + scrollView.height / 2
        //  最终的中心
        let currentCenter = CGPoint(x: currentCenterX, y: currentCenterY)
        //  通过中心点获取indexpath
        if let indexPath = emoticonCollectionView.indexPathForItem(at: currentCenter) {
            let section = indexPath.section
            
            //  滚动到指定组
            toolBar.selectedButton(section: section)
            setPageControlData(indexPath: indexPath)
        }
        
        
        
        
    }
    
    
}

